/**
 *ZHU framework. Copyright 2007-, all rights reserved.
 *
 * $Id$
 * $Revision$
 * $Date$
 * $Author$
 */
package daily.service;

import java.util.*;

import javax.ejb.*;
import javax.persistence.*;

import zhu.framework.service.*;

import com.google.common.collect.*;

import daily.entity.*;
import daily.entity.security.*;

/**
 * @author xiaopengzhu
 * 
 */
@Stateless
public class StaffGroupServiceImpl extends AbstractPersistenceOperationService {

	public void deleteStaffGroup(final StaffGroup selectStaffGroup) {
		final StaffGroupLifecycle lifecycle = getLifecycleFactory().getLifecycle(StaffGroupLifecycle.class);
		lifecycle.remove(selectStaffGroup);
	}

	public List<StaffGroup> getStaffGroupList() {
		final StaffGroupLifecycle lifecycle = getLifecycleFactory().getLifecycle(StaffGroupLifecycle.class);
		return lifecycle.findAll();
	}

	public void saveStaffGroup(final StaffGroup selectStaffGroup) {
		final StaffGroupLifecycle lifecycle = getLifecycleFactory().getLifecycle(StaffGroupLifecycle.class);
		try {
			if (selectStaffGroup.getEntityId() == null) {
				lifecycle.create(selectStaffGroup);
			} else {
				lifecycle.update(selectStaffGroup, null);
			}
		} catch (final OptimisticLockException e) {
			throw new BusinessException(e.getMessage());
		}
	}

	public StaffGroup getStaffGroupPermission(final StaffGroup selectStaffGroup) {
		final StaffGroupLifecycle lifecycle = getLifecycleFactory().getLifecycle(StaffGroupLifecycle.class);
		final StaffGroup staffGroup = lifecycle.findById(selectStaffGroup.getEntityId());
		final EnumSet<Function> set = EnumSet.noneOf(Function.class);
		for (final FunctionSecuritySetting fs : staffGroup.getFunctionSecuritySettings()) {
			set.add(fs.getFunction());
		}
		for (final Function f : Function.values()) {
			if (set.contains(f) == false) {
				staffGroup.getFunctionSecuritySettings().add(createFunctionSecuritySetting(f));
			}
		}
		return staffGroup;
	}

	private FunctionSecuritySetting createFunctionSecuritySetting(final Function f) {
		final FunctionSecuritySetting setting = new FunctionSecuritySetting();
		setting.setFunction(f);
		final SortedSet<SecurityRole> securityRoles = Sets.newTreeSet(f.getSecurityRoles());
		setting.setSecurityRole(securityRoles.last());
		return setting;
	}

}
